package com.itmuch.cloud.study.user.controller;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import com.itmuch.cloud.study.core.utils.JsonBeanUtils;
import com.itmuch.cloud.study.user.entity.Article;
import com.itmuch.cloud.study.user.service.DataService;
import com.itmuch.cloud.study.user.service.SSEServer;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "DataPush模块")
@RestController
public class DataPushController
{
    long init = 0L;
    
    @Autowired
    DataService dataService;
    
    @PostConstruct
    private void init()
    {
        log.info("Server-Sent Events start");
        new ScheduledThreadPoolExecutor(2).scheduleAtFixedRate(() -> {
            long now = (init + RandomUtils.nextInt(5, 10)) % 101;
            SSEServer.batchSendMessage(String.valueOf(init));
            if (now < init)
            {
                try
                {
                    // 随机选择2个，返回访问量小的
                    List<Article> articles = dataService.getArticles();
                    int length = articles.size();
                    Article article001 = articles.get(RandomUtils.nextInt(0, length));
                    Article article002 = articles.get(RandomUtils.nextInt(0, length));
                    SSEServer.batchSendMessage("json", JsonBeanUtils.beanToJson(article001.getViewCount() > article002.getViewCount() ? article002 : article001, false));
                }
                catch (IOException e)
                {
                }
            }
            init = now;
        }, 2000, 1000, TimeUnit.MILLISECONDS);
    }
    
    @CrossOrigin
    @GetMapping("/sse/connect/{userId}")
    public SseEmitter connect(@PathVariable String userId)
    {
        return SSEServer.connect();
    }
}
